package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.threadLocal.UserThreadLocal;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.vo.CountVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 预约信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-31
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private IFamilyMemberService familyMemberService;

    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     *
     * @param dto 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(ReservationDto dto) {
        //如果预取消约数量大于3则不让预约
        Long userId = UserThreadLocal.getUserId();
        int count = getCancelledReservationCount(userId);
        if (count >= 3) {
            throw new RuntimeException("您已取消预约3次，请勿重复预约");
        }
        Reservation reservation = new Reservation();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.parse(dto.getTime(), formatter);
        reservation.setTime(time);
        reservation.setStatus(0);
        BeanUtils.copyProperties(dto, reservation);


        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 获取预约取消数量
     * @param userId
     * @return
     */
    @Override
    public int getCancelledReservationCount(Long userId) {

        FamilyMember member = familyMemberService.getById(userId);
        // 获取当前时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        long count = count(new LambdaQueryWrapper<Reservation>()
                .eq(Reservation::getMobile, member.getPhone())
                .eq(Reservation::getStatus, 2)
                .lt(Reservation::getTime, endTime));
        return Math.toIntExact(count);
    }

    /**
     * 根据时间获取预约数量
     *
     * @param time
     * @return
     */
    @Override
    public List<CountVo> getReservationCountByTime(Long time) {
        // 获取目标时间
        LocalDateTime targetTime = LocalDateTimeUtil.of(time);

        // 设置查询时间范围：当天0点到18:30
        LocalDateTime startTime = targetTime.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusHours(18).plusMinutes(30);

        // 一次性查询该时间段内的所有预约记录
        List<Reservation> reservations = list(new LambdaQueryWrapper<Reservation>()
                .ge(Reservation::getTime, startTime)
                .lt(Reservation::getTime, endTime)
                .eq(Reservation::getStatus, 0)); // 只查询有效预约状态

        List<CountVo> result = new ArrayList<>();
        int maxCapacity = 6; // 每个时间段最多可预约6次
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //遍历reservations封装result
        // 使用Map统计每个具体时间点的预约数量
        Map<String, Integer> timeCountMap = new HashMap<>();

        // 遍历预约记录，统计每个具体时间点的预约数量
        for (Reservation reservation : reservations) {
            String reservationTime = reservation.getTime().format(formatter);
            // 累加该时间点的预约数量
            timeCountMap.put(reservationTime, timeCountMap.getOrDefault(reservationTime, 0) + 1);
        }

        timeCountMap.forEach((timeString, count) -> {
            CountVo countVo = new CountVo();
            countVo.setTime(timeString);
            countVo.setCount(maxCapacity - count);
            result.add(countVo);
        });

        return result;
    }

    @Override
    public boolean cancel(Long id) {
        Reservation reservation = getById(id);
        if (reservation != null) {
            reservation.setStatus(2);
            return updateById(reservation);
        }
        return false;
    }
}
